/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.flexengine.utils;

import com.flexengine.logger.Logger;
import java.lang.reflect.Field;

/**
 * @author Luann R. Athayde
 * @version 1.0
 * @since 1.0
 */
public class Reflection {
    
    private static Field getBasicField(String name, Object item) {
        try {
            Field field = null;
            Class tmpClass = item.getClass();
            while( tmpClass!=null ) {
                try {
                    field = tmpClass.getDeclaredField(name);
                    field.setAccessible(true);
                    return field;
                } catch(NoSuchFieldException noe) {
                }
                tmpClass = tmpClass.getSuperclass();
            }
            return field;
        } catch(SecurityException e) {
            Logger.logError(item.getClass().getName()+" - ERROR: "+e);
        }
        return null;
    }
    
    public static Field getField(String name, Object item) {
        try {
            if( name.contains(".") ) {
                String fieldNames[] = name.split("\\.");
                Field field = getBasicField(fieldNames[0], item);
                if( field!=null ) {
                    Object tmpItem = item;
                    for( int i=1;i<fieldNames.length;i++ ) {
                        tmpItem = field.get(tmpItem);
                        field = getBasicField(fieldNames[i], tmpItem);
                    }
                    return field;
                }
            } else {
                return getBasicField(name, item);
            }
        } catch(IllegalArgumentException | IllegalAccessException e) {
            Logger.logError(item.getClass().getName()+" - ERROR: "+e);
        }
        return null;
    }
    
}
